package com.zh.mp.demo.modules.demo.entity;

import cn.hutool.core.util.ArrayUtil;
import com.fasterxml.jackson.annotation.JsonBackReference;
import com.zh.mp.demo.modules.demo.entity.base.AbstractModel;
import lombok.*;
import org.apache.commons.lang3.builder.ReflectionToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;

import javax.persistence.*;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

@EqualsAndHashCode(callSuper = true)
@Setter
@Getter
@NoArgsConstructor
@AllArgsConstructor
@Builder
@Entity
@Table(name = "orm_department")
//@ToString(callSuper = true)
public class OrmDepartment extends AbstractModel {//OrmDepartmentRepository
    /**
     * 部门名
     */
    @Column(name = "name", columnDefinition = "varchar(255) not null")
    private String name;

    /**
     * 上级部门id
     */
    @ManyToOne(cascade = {CascadeType.REFRESH}, optional = true)
    @JoinColumn(name = "superior", referencedColumnName = "id")
    private OrmDepartment superior;
    /**
     * 所属层级
     */
    @Column(name = "levels", columnDefinition = "int not null default 0")
    private Integer levels;
    /**
     * 排序
     */
    @Column(name = "order_no", columnDefinition = "int not null default 0")
    private Integer orderNo;
    /**
     * 子部门集合
     */
    @OneToMany(cascade = {CascadeType.REFRESH, CascadeType.REMOVE}, fetch = FetchType.EAGER, mappedBy = "superior")
    private Collection<OrmDepartment> children;

    /**
     * 部门下用户集合
     */
    @JsonBackReference
    @ManyToMany(mappedBy = "departmentList", fetch = FetchType.EAGER)
    private Collection<OrmUser> userList;

    @Override
    public String toString()
    {
        String[] fields = new String[]{"userList"};
        //MULTI_LINE_STYLE 每一行一个字段
        //SHORT_PREFIX_STYLE 不换行，用逗号分隔
        ReflectionToStringBuilder builder = new ReflectionToStringBuilder(this, ToStringStyle.SHORT_PREFIX_STYLE) {
            @Override
            protected boolean accept(Field field) {
                return !ArrayUtil.contains(fields, field.getName());
            }
        };

        return builder.toString();
    }
}
